/**************************************************************
  > File Name: du_glob.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2021年12月16日 星期四 14时38分58秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <glob.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATHSIZE 1024


static int noloop(const char *path)
{
	char *pos = NULL;
	pos = strrchr(path,'/');
	if (pos == NULL)
			exit(1);
	if (strcmp(pos+1,".") == 0 || strcmp(pos+1,"..") == 0)
			return 0;
	return 1;
}


int64_t mydu(const char *path)
{
	glob_t glob_line;
	static struct stat statbuf;
	static char nextpath[PATHSIZE] = {0};
	int i = 0;
	int64_t count = 0;

	if (lstat(path,&statbuf) < 0)
	{
			perror("lstat()");
			exit(1);
	}

	if (!S_ISDIR(statbuf.st_mode))
	{
			return statbuf.st_blocks;
	}

	strncpy(nextpath,path,PATHSIZE-1);
	strcat(nextpath,"/*");
	glob(nextpath,0,NULL,&glob_line);

	strncpy(nextpath,path,PATHSIZE-1);
	strcat(nextpath,"/.*");
	glob(nextpath,GLOB_APPEND,NULL,&glob_line);

	count = statbuf.st_blocks;;
	for (i = 0; i < glob_line.gl_pathc; i++)
	{
		if (noloop(glob_line.gl_pathv[i]))	
			count += mydu(glob_line.gl_pathv[i]);
	}
	globfree(&glob_line);
	return count;
}


int main(int argc,char **argv)
{

	if (argc < 2)
	{
		fprintf(stderr,"Usage\n");
		exit(1);
	}
	
	printf("%ld\n",mydu(argv[1])/2);
    exit(0);
}
